package com.wangbl.manager;

import java.util.HashMap;

import com.wangbl.manager.ScanDevice.OnScanFoundDeviceListener;
import com.wangbl.manager.ScanDeviceUtil.OnSearchReceiveListener;
import com.wangbl.manager.constant.Action;
import com.wangbl.manager.constant.Notify;
import com.wangbl.manager.model.DevInfo;
import com.wangbl.manager.utils.Logger;

import android.content.Context;
import android.os.Message;

public class HandleAction {

	protected static final String TAG = "HandleAction";
	private Manager manager;
	private ScanDeviceUtil scan;
	private Controller controller;
	public volatile boolean isInterrupt;

	// private ScanDevice scan ;

	public HandleAction(Context ctx, Manager manager) {
		this.manager = manager;
		scan = new ScanDeviceUtil(ctx);
		controller = new Controller();
		// scan = new ScanDevice(ctx);
	}

	public void handle(Message msg) {
		isInterrupt = false;
		switch (msg.what) {
		case Action.ACTION_SCAN:
			scan.startDevSearch(20000, listener);
			// scan.startScan(0, listener);
			break;
		case Action.ACTION_STOP_SCAN:
			scan.stopSearch();
			break;
		case Action.ACTION_CONNECT:
			boolean resVal = controller.connect((DevInfo) msg.obj);
			Logger.i(TAG, "conn reaVal:" + resVal);
			if(resVal){
				manager.notifyEmptyMessage(Notify.NOTIFY_CONNECT_SUCCESS);
			} else {
				manager.notifyEmptyMessage(Notify.NOTIFY_CONNECT_FAIL);
			}
			break;
		case Action.ACTION_WRITE:
			String cmd = (String) msg.obj;
			if("i".equals(cmd) || "j".equals(cmd)){
				while(!isInterrupt){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					controller.write(cmd);
				}
			} else {
				controller.write(cmd);
			}
			break;
		case Action.ACTION_DISCONNECT:
			controller.disconntect();
			break;
		}
	}

	private OnSearchReceiveListener listener = new OnSearchReceiveListener() {

		@Override
		public void stateTurningOff() {
			manager.notifyEmptyMessage(Notify.NOTIFY_SCAN_FINISH);
			scan.stopSearch();
		}

		@Override
		public void startDiscoveryFail() {
			manager.notifyEmptyMessage(Notify.NOTIFY_SCAN_FINISH);
			scan.stopSearch();
		}

		@Override
		public void onFindFinished() {
			manager.notifyEmptyMessage(Notify.NOTIFY_SCAN_FINISH);
			scan.stopSearch();
		}

		@Override
		public void onFindDevTimeout() {
			manager.notifyEmptyMessage(Notify.NOTIFY_SCAN_FINISH);
			scan.stopSearch();
		}

		@Override
		public void onFindDevReceive(HashMap<String, DevInfo> devInfos) {
			manager.notifyMessage(Notify.NOTIFY_ON_FOUNE_DEVICE, 0, 0, devInfos);
		}

		@Override
		public void onClosedBtooth() {
			Logger.i(TAG, "onClosedBtooth");
			manager.notifyEmptyMessage(Notify.NOTIFY_SCAN_CLOSE_BT);
			scan.stopSearch();
		}

		@Override
		public void onConnectLose() {
			manager.notifyEmptyMessage(Notify.NOTIFY_CONNECT_LOSE);
		}
		
		
	};
}
